
package simple;

class Solution21 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        //创建虚拟头节点
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;

        //双指针
        ListNode p1 = list1;
        ListNode p2 = list2;

        //p1、p2比较小的拼接到p
        while(p1 != null && p2 != null){
            if(p1.val <= p2.val){
                //拼接
                p.next = p1;
                //指针后移
                p1 = p1.next;
            } else {
                p.next = p2;
                //指针后移
                p2 = p2.next;
            }
            //一次拼接，p后移
            p = p.next;
        }

        //比较完大小，p1未完，之间拼接
        if(p1 != null){
            p.next = p1;
        }

        if(p2 != null) {
            p.next = p2;
        }

        return dummy.next;
    }
}